package com.fsl.facebook;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Hex;

import com.fsl.facebook.model.FaceBookContext;

/**
 * 
 * 
 * 
 * 
 * @author joaquindiez
 * 
 */
public class FaceBookCookieHelper {

	private String apikey;
	private String apiSecret;

	public FaceBookCookieHelper(String apikey, String apiSecret) {
		this.apikey = apikey;
		this.apiSecret = apiSecret;
	}

	/**
	 * Return null if no facebook cookie found or if is not valid
	 * 
	 * if the cookie is valid.. return it as a FaceBookContext
	 * 
	 * @return
	 */
	public FaceBookContext findFaceBookContext(Map<String, String> cookieMap) {

		FaceBookContext ctx = null;

		if (cookieMap != null) {

			String cookievalue = findCookieFacebook(cookieMap);

			if (cookievalue != null) {
				HashMap<String, String> fbatt = validateFacebookCookie(cookievalue);

				if (!fbatt.isEmpty()) {
					ctx = new FaceBookContext();

					ctx.setAccess_token(fbatt.get("access_token"));
					ctx.setSession_key(fbatt.get("session_key"));
					ctx.setSig(fbatt.get("sig"));
					ctx.setUid(fbatt.get("uid"));
				}
			}
		}

		return ctx;
	}

	private String findCookieFacebook(Map<String, String> cookieMap) {
		if (cookieMap != null) {
			String key = "fbs_" + apikey;
			if (cookieMap.containsKey(key)) {

				String cookieFb = cookieMap.get(key);
				return cookieFb;
			}
		}

		return null;
	}

	@SuppressWarnings("deprecation")
	private HashMap<String, String> validateFacebookCookie(String cookievalue) {

		HashMap<String, String> fbatt = new HashMap<String, String>();
		java.net.URLDecoder urlDecode = new java.net.URLDecoder();

		boolean ret = false;
		String[] split = cookievalue.split("&");

		Arrays.sort(split);

		StringBuffer payload = new StringBuffer();

		String signature = null;

		for (String s : split) {

			String keyvalue[] = s.split("=");

			fbatt.put(keyvalue[0], urlDecode.decode(keyvalue[1]));

			if (!s.startsWith("sig")) {

				payload.append(urlDecode.decode(s));
			} else {

				signature = s;
			}
		}

		String r = payload.toString();

		try {
			MessageDigest md = MessageDigest.getInstance("MD5");

			r = r + apiSecret;
			byte[] digest = md.digest(r.getBytes());

			String md5St = Hex.encodeHexString(digest);

			md5St = "sig=" + md5St;

			if (!md5St.equals(signature)) {
				fbatt.clear();
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return fbatt;
	}
}
